<?php
namespace SimpleMVC\lib;

class Captcha {
	
	private static $chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
	
	private $width = 80;
	private $height = 30;
	private $pixels = 0;
	private $lines = 0;
	
	public function getWidth()
	{
		return $this->width;
	}
	
	public function setWidth($width)
	{
		$this->width = $width;
	}
	
	public function getHeight()
	{
		return $this->height;
	}
	
	public function setHeight($height)
	{
		$this->height = $height;
	}
	
	public function getPixels()
	{
		return $this->pixels;
	}
	
	public function setPixels($pixels)
	{
		$this->pixels = $pixels;
	}
	
	public function getLines()
	{
		return $this->lines;
	}
	
	public function setLines($lines)
	{
		$this->lines = $lines;
	}
	
	public function generateCode($length = 4)
	{
		if ($length < 4) {
			$length = 4;
		}
		$chars = str_shuffle(self::$chars);
		return substr($chars, 0, $length);
	}
	
	public function create($code)
	{
		//创建黑色画布
		$image = imagecreatetruecolor($this->width, $this->height);
		//为画布定义(背景)颜色
		$bgColor = imagecolorallocate($image, 255, 255, 255);
		//填充颜色
		imagefill($image, 0, 0, $bgColor);
		//创建一个变量存储产生的验证码数据，便于用户提交核对
		for ($i = 0, $length = strlen($code); $i < $length; $i++)
		{
			// 字体大小
			$fontSize = 14;
			// 字体颜色
			$fontColor = imagecolorallocate($image, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100));
			// 显示的坐标
			$x = ($i * $this->width / $length) + 5;
			$y = mt_rand(5, 10);
			// 填充内容到画布中
			imagestring($image, $fontSize, $x, $y, $code{$i}, $fontColor);
		}
		//设置干扰点
		for ($i = 0; $i < $this->pixels; $i++)
		{
			$pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
			imagesetpixel($image, mt_rand(1, 99), mt_rand(1, 29), $pointcolor);
		}
		//设置干扰线
		for ($i = 0; $i < $this->lines; $i++)
		{
			$linecolor = imagecolorallocate($image, mt_rand(150, 230), mt_rand(150, 230), mt_rand(150, 230));
			imageline($image, mt_rand(1, 99), mt_rand(1, 29), mt_rand(1, 99), mt_rand(1, 29), $linecolor);
		}
		//向浏览器输出图片头信息
		header('Content-Type: image/jpeg');
		//输出图片到浏览器
		imagejpeg($image);
		//销毁图片
		imagedestroy($image);
	}
}